package com.langsin.util;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class CreateImageAction extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Random random = new Random();
        String randStr = "0123456789asdfghjklqwertyiopzxcvbnm";
        BufferedImage image = new BufferedImage(80,40,BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.fillRect(0,0,80,40);
        for(int i = 0;i < 10;i ++){
            int x1 = random.nextInt(20);
            int y1 = random.nextInt(40);
            int x2 = random.nextInt(60)+20;
            int y2 = random.nextInt(40);
            graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
            graphics.drawLine(x1,y1,x2,y2);
        }
        graphics.translate(5,5);//偏移
        StringBuffer buffer = new StringBuffer();
        for(int i = 0;i < 4;i++){
            char ch = randStr.charAt(random.nextInt(randStr.length()));
            String str = String.valueOf(ch);
            int type = 0;
            if(random.nextBoolean()){
                str = str.toUpperCase();
                type = Font.ITALIC;
            }else{
                type = Font.PLAIN;
            }
            graphics.setFont(new Font("@华文隶书",type,18));
            if(i == 0){
                graphics.setColor(new Color(48,154,233));
            }
            if(i == 1){
                graphics.setColor(new Color(68,213,199));
            }
            if(i == 2){
                graphics.setColor(new Color(21,40,213));
            }
            if(i == 3){
                graphics.setColor(new Color(175,58,122));
            }
            graphics.drawString(str,i * 18,25);
            buffer.append(str);
        }
        HttpSession session = request.getSession();
        session.setAttribute("ImageCode",buffer.toString().toLowerCase());
        graphics.dispose();
        ImageIO.write(image,"JPEG",response.getOutputStream());
    }
}
